﻿
@{
    Layout = null;
}

<div>
    <div class="col-3 pr-0" style="display: none">
        <label id="Common-ManageFile-Domain">@ViewData["Domain"]</label>
        <label id="Common-ManageFile-DomainId">@ViewData["DomainId"]</label>
        <label id="Common-ManageFile-Parent-ModalID">@ViewData["ModalID"]</label>
    </div>
    <div class="input-group" style="padding-bottom:10px">
        <div class="col-2 pr-0 pl-0">
            <span class="input-group-text font-rfs border-radius-noright noRightBorder">上传附件</span>
        </div>
        <div class="col-6 pl-0 input-group">
            <input id="Common-ManageFile-file" type="file" multiple class="form-control font-rfs border-radius-noleft" style="width: 87%; padding-top: 4px;" data-id="" />
            <button id="Common-ManageFile-UploadFile" class="input-group-text font-rfs border-radius-noleft noLeftBorder" style="width: 13%; padding-left: 0.1rem; padding-top: 0px; padding-bottom: 0px; margin-bottom: 1px;" title="上传附件">
                <i class="bi-cloud-upload" style="font-size:18px"></i>
            </button>
        </div>
        <div class="col-4 pl-0 input-group">
            <button id="Common-ManageFile-deleteFile" class="btn font-rfs" style="margin-top: 1px;"><i class="bi-trash"></i> 删除</button>
            <button id="Common-ManageFile-dowloadFile" class="btn font-rfs" style="margin-top: 1px;"><i class="bi-cloud-download"></i> 下载</button>
        </div>
    </div>
</div>
<div class="table-responsive-sm modal-table-shadow p-0 bg-white rounded col-md-12 pre-scrollable" style="height: 40vh;">
    <table id="Common-ManageFile-AttachmentList" class="table table-striped table-sm table-hover">
        <thead style="font-size: calc(0.5em + 0.1vw) !important">
            <tr>
                <th>Id</th>
                <th>文件名</th>
                <th>文件类型</th>
                <th>文件大小</th>
                <th>上传时间</th>
                <th>上传人</th>
            </tr>
        </thead>
        <tbody style="font-size: calc(0.6em + 0.1vw) !important"></tbody>
    </table>
</div>
<div class="text-right" style="padding-top: 5px;">
    <button id="Common-ManageFile-cancel" type="button" class="btn btn-info font-rfs">关闭</button>
</div>
<div class="modal" id="Common-ManageFile-DeleteConfirm" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class='modal-header'>
                <p class="pt-3 pl-3 font-rfs">删除</p>
            </div>
            <div class="modal-body">
                <p class="font-rfs">确认删除当前选中记录吗？</p>
            </div>
            <div class="modal-Delete-footer">
                <button id="Common-ManageFile-dc-delete" class="btn btn-outline-primary border-radius-noradius noLeftBorder noRightBorder font-rfs" style="width:50%; height:fit-content">删除</button>
                <button id="Common-ManageFile-dc-cancel" class="btn btn-outline-primary border-radius-noradius noRightBorder font-rfs" style="width:50%; height:fit-content">取消</button>
            </div>
        </div>
    </div>
</div>

<script>
    var manageAttachment_uploadFileId = "";
    var manageAttachment_uploadFileName = "";

    $(document).ready(function () {
        $("#Common-ManageFile-Domain").val(getUrlParam("Domain"));
        $("#Common-ManageFile-DomainId").val(getUrlParam("DomainId"));
        $("#Common-ManageFile-Parent-ModalID").val(getUrlParam("ModalID"));

        LoadAttachmentList();
    });

    function SetFileName(value, row, index) {
        return "<input class='table-cell-input' " + "onchange='UpdateFileName(this)' value='" + value + "'/>";
    }

    function UpdateFileName(obj) {
        var fileName = $(obj).val();
        var id = $(obj).parent().parent().attr('data-uniqueid');

        $.post("/Common/UpdateFileName", {
            Id: id,
            newFileName: fileName
        }, function (data) {
            if (data.indexOf("成功") == -1) {
                alert(data);
            }
        });
    }

    function LoadAttachmentList() {
        var manageAttachment_columns = [{ field: "id", visible: false }, { field: "fileName", formatter: SetFileName },
        { field: "fileType" }, { field: "fileSize" }, { field: "uploadTime", formatter: SetTime }, { field: "createByName" }];

        $('#Common-ManageFile-AttachmentList').bootstrapTable('destroy');
        $('#Common-ManageFile-AttachmentList').bootstrapTable({
            method: 'post',
            url: "/Common/GetUploadFileList",
            dataType: "json",  // 服务器端返回值类型
            contentType: "application/x-www-form-urlencoded; charset=UTF-8", // 如果是 POST 请求，这个属性必须加
            queryParams: function (params) {
                var data = {
                    Domain: $("#Common-ManageFile-Domain").html(),
                    DomainId: $("#Common-ManageFile-DomainId").html(),
                };
                return data;
            }, //参数
            queryParamsType: "search", //参数格式,发送标准的RESTFul类型的参数请求

            uniqueId: "id",          // 设置主键
            locale: "zh-CN",
            columns: manageAttachment_columns,
            onClickRow: function (row, $element, field) {
                $("#Common-ManageFile-AttachmentList").find("tbody").find("tr").each(function () {
                    $(this).removeClass('changeblueColor');
                });
                $element.addClass("changeblueColor");
                manageAttachment_uploadFileId = row.id;
                manageAttachment_uploadFileName = row.fileName;
            },
            silent: true,  //刷新事件必须设置
            formatLoadingMessage: function () {
                return "请稍等，正在加载中...";
            },
            formatNoMatches: function () {  //没有匹配的结果
                return '无符合条件的记录';
            },
            onLoadError: function (data) {
                $('#Common-ManageFile-AttachmentList').bootstrapTable('removeAll');
            },
            onLoadSuccess: function (data) {   // 数据加载成功后触发该事件
                $('.fixed-table-toolbar').css("height", "0px"); /* 隐藏表格上的工具栏 */
            }
        });
    }

    function SetTime(value, row, index) {
        return value == null ? '-' : value.replace('T', ' ').split('.')[0];
    }

    $("#Common-ManageFile-cancel").click(function (event) {
        var modalID = $("#Common-ManageFile-Parent-ModalID").html();
        $("#" + modalID).modal('hide');
    });

    $("#Common-ManageFile-dc-cancel").click(function (event) {
        $("#Common-ManageFile-DeleteConfirm").modal('hide');
    });

    $("#Common-ManageFile-deleteFile").click(function (event) {
        if (manageAttachment_uploadFileId.length > 0) {
            $("#Common-ManageFile-DeleteConfirm").modal({
                backdrop: 'static',
                keyboard: false
            });
        }
    });

    $("#Common-ManageFile-dc-delete").click(function () {
        $.post("/Common/postDeleteFile", {
            FileId: manageAttachment_uploadFileId
        }, function (data) {
            if (data.indexOf("成功") >= 0) {
                LoadAttachmentList();
            } else {
                alert(data);
            }
        });

        $("#Common-ManageFile-DeleteConfirm").modal('hide');
    });

    $("#Common-ManageFile-dowloadFile").click(function (event) {
        if (manageAttachment_uploadFileId.length > 0) {
            var mime = getMIMEType(manageAttachment_uploadFileName);
            if (mime == null) {
                alert("该类型文件不提供下载服务！");
                return false;
            }

            var formData = new FormData();
            formData.append("downloadFileId", manageAttachment_uploadFileId);

            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/Common/postDownloadFile', true);
            xhr.responseType = "blob";  // 这个是关键
            xhr.onload = () => {
                const blob = new Blob([xhr.response], { type: mime + ",charset=utf-8" });
                const blobUrl = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = blobUrl;
                a.download = manageAttachment_uploadFileName; // 复制文件名
                a.target = '_blank';
                a.click();
            }
            xhr.send(formData);
        }
    });

    $("#Common-ManageFile-UploadFile").click(function (event) {
        var formData = new FormData();
        var name = $("#Common-ManageFile-file").val();
        $.each($("#Common-ManageFile-file")[0].files, function (index, value) { // 支持多文件上传
            formData.append('file', $("#Common-ManageFile-file")[0].files[index]);
        });
        formData.append("Domain", $("#Common-ManageFile-Domain").html()); // 上传文件时附加的参数
        formData.append("DomainId", $("#Common-ManageFile-DomainId").html());

        $.ajax({
            url: '/Common/UploadFileSave',
            type: 'POST',
            data: formData,
            async: true,
            cache: false,
            processData: false,// 告诉jQuery不要去处理发送的数据
            contentType: false,// 告诉jQuery不要去设置Content-Type请求头
            success: function (data) {  
                if (data.indexOf("成功") >= 0) {
                    $("#Common-ManageFile-file").val("");
                    LoadAttachmentList();
                } else {
                    alert(data);
                }
            },
            error: function (returndata) {
                //alert(returndata);
            }
        });
    });

    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        
        if (r != null) {
            return unescape(r[2]);
        }

        return null; //返回参数值
    }

</script>
